import 'package:animation/api/video.dart';
import 'package:animation/components/AlertDialog/my_loading.dart';
import 'package:animation/components/empty.dart';
import 'package:animation/components/images/image_load.dart';
import 'package:animation/model/options_base.dart';
import 'package:animation/pages/other/videos/bilibili_page.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class BilibiliSearch extends StatefulWidget {
  final String keyword;
  final bool change;
  const BilibiliSearch({
    super.key,
    required this.keyword,
    required this.change,
  });

  @override
  State<BilibiliSearch> createState() => _SearchPageState();
}

class _SearchPageState extends State<BilibiliSearch>
    with AutomaticKeepAliveClientMixin {
  TextEditingController controller = TextEditingController();
  ScrollController scrollController = ScrollController();
  bool isLoading = false;
  String intro = '';
  List videoList = [];

  void getAnimation(String msg) async {
    setState(() {
      isLoading = true;
    });
    try {
      if (!mounted) return;
      Response res = await getVideo(msg: msg);
      setState(() {
        videoList = res.data['data'];
      });
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    if (widget.keyword.isNotEmpty) {
      getAnimation(widget.keyword);
    }
  }

  // 监听 change 变化
  @override
  void didUpdateWidget(covariant BilibiliSearch oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.change != widget.change) {
      setState(() {
        videoList = [];
        isLoading = true;
      });
      getAnimation(widget.keyword);
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Padding(
      padding: const EdgeInsets.all(4),
      child: Column(
        children: [
          if (videoList.isNotEmpty)
            Expanded(
              child: GridView.builder(
                  itemCount: videoList.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: OptionsBase().horizontalColumns(context),
                    crossAxisSpacing: OptionsBase().padding,
                    mainAxisSpacing: OptionsBase().padding,
                    childAspectRatio: 0.7,
                  ),
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => BilibiliPage(
                                      msg: videoList[index]['title'],
                                      ssid: videoList[index]['ss_id'],
                                      cover: videoList[index]['cover'],
                                    )));
                      },
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5),
                            color:
                                Theme.of(context).colorScheme.primaryContainer,
                            boxShadow: [
                              BoxShadow(
                                color: Theme.of(context).colorScheme.shadow,
                                offset: Offset(1, 2),
                                blurRadius: 2,
                              ),
                            ]),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(5),
                          child: Stack(
                            alignment: Alignment.bottomCenter,
                            children: [
                              Hero(
                                tag: videoList[index]['ss_id'],
                                child: ImageLoad(
                                    imageUrl: videoList[index]['cover']),
                              ),
                              Container(
                                padding: EdgeInsets.only(
                                    left: 5, right: 5, top: 2, bottom: 2),
                                color: const Color.fromARGB(24, 158, 158, 158),
                                width: double.infinity,
                                child: Text(
                                  videoList[index]['title'],
                                  style: TextStyle(
                                    color: Colors.white,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    );
                  }),
            ),
          if (videoList.isEmpty && isLoading == false) Empty(),
          if (isLoading)
            Expanded(
              child: MyLoading(
                size: 50,
              ),
            ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
